define(["../common"], function() {

	var $form = $("#addForm");
	var $msgWrap = $("#msgWrap");
	var addDoPath = g_shopDomain + "/storeRegion/addDo/json";
	var delDoPath = g_shopDomain + "/storeRegion/delDo/json";

	var formConfig = {
		fields: {
			"id.regionId": {
				rule: "required",
				msg: {required: "请选择配送地区"},
				target: $msgWrap
			}
		},
		valid: function(form) {
			var regionId = $("#regionId").val();
			if ($("#item_" + regionId).length > 0) {
				$form.showMsg("已经存在", 'error');
				return;
			}
			if (!$form.showMsg("正在添加...", 'load', true)) return;
			
			var regionPath = $("#regions select option:selected").map(function(){
				return $(this).text();
			}).get().join(" ");
			$("#regionPath").val(regionPath);
			
			$.post(addDoPath, $form.serialize(), function(data) {
				if (data.status !== 0) {
					$form.showMsg(data.message, 'error');
					return;
				} 
				$form.showMsg("添加成功", 'pass');
				
				$("#list").append(
					'<tr id="item_' + regionId + '">' + 
				    ' <td>' + regionPath + '</td>' +
				    ' <td class="cz"><a href="javascript:;" id="del_' + regionId + '">删除</a></td>' +
				    '</tr>'		
				);
			});
		}
	};

	loadjs(["validator"], function() {
		$form.validator(formConfig);
	});

	loadjs(["region"], function() {
		//加载地区并生成下拉列表
		$("#regions").regionsSelect({
			minType: 3,
			value: $("#regionId").val(), 
			onSelect: function($select) {
				$("#regionId").val($select.val());
			}
		});
		
	});

	// 事件:添加
	$("#submitBt").click(function() {
		$form.trigger('validate');
	});

	// 事件：删除
	$(document).on("click", "[id^='del_']", function() {
		var regionId = ($(this).attr("id").split("_"))[1];
		var $item = $("#item_" + regionId);
		if ($item.doing()) return;
		
		var msgConfig = {
			id: "del_" + regionId,
			type: 'confirm',
			content: "确定要删除吗？",
			title: "提示",
			onClose: function() {
				if (this.val()) {
					$item.showMsg("正在删除...", 'load', true);
					$item.fadeTo(null,0.1);
					$.getJSON(delDoPath, {regionId: regionId}, function(data) {
						if (data.status === 0) {
							$item.fadeOut(function() {
								$item.showMsg();
								$(this).remove();
							});
						} else {
							$item.showMsg(data.message, 'error');
							$item.fadeTo('fast',1);
						}
					});
				}
			}
		};
		loadjs(["msgbox"], function() {
			$.msgbox(msgConfig);
		});
		
	});
});
